package kr.hkit.androidcomplete02.ch19;

import kr.hyunist.androidcomplete01.*;
import android.app.*;
import android.content.*;
import android.content.DialogInterface.OnCancelListener;
import android.os.*;
import android.view.*;
import android.widget.*;

public class LongTime4Ex extends Activity {
	int mainValue;
    TextView mText;
    ProgressDialog mProgress;
    boolean mQuit;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ch19_upload);
        mText=(TextView)findViewById(R.id.ch19_uploadtv);
    }
    
    public void mOnClick(View v) {
        mProgress =new ProgressDialog(this);
        mProgress.setTitle("Updating");
        mProgress.setMessage("Wait...");
        mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgress.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                mQuit = true;
                mProgress.dismiss();                
            }
        });
        mProgress.show();
        mQuit = false;
        UpdateThread thread = new UpdateThread(mainValue);
        thread.start();
    }

    
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
        	int mValue = msg.arg1;
        	mainValue = mValue;
            
            if (mValue <= 100 && mQuit == false) {
            	mText.setText(Integer.toString(mValue));
                mProgress.setProgress(mValue);
            } else {
            	mQuit = true;
                mProgress.dismiss();
            }
        }
    };

    class UpdateThread extends Thread{
    	int mValue;
    	
    	public UpdateThread(int mValue) {
    		if (mValue >= 100) mValue = 0;
			this.mValue = mValue; 
		}

		public void run() {
    		
    		while(mQuit==false){
    			mValue++;
    			Message msg = mHandler.obtainMessage(0, mValue, 0);
    			mHandler.sendMessage(msg);
    			try { Thread.sleep(50); } 
                catch (InterruptedException e) {;}
    		}
    	}
    }
}